import haxe.io.Path;
import haxe.Json;
import sys.io.File;
import sys.FileSystem;

using StringTools;

class Main {
	private static var keys:Map<String, Bool> = [];

	private static var list:Array<{text:String, by:String}> = [];

	private static var languageJson:Map<String, Bool>;

	private static var igrone:String;

	static function main() {
		var text = "";
		var args = Sys.args();
		igrone = File.getContent("./igrone.txt");
		for (index => dir in args) {
			switch (index) {
				case 0:
					// 初始化已翻译的语言JSON
					if (FileSystem.exists(dir)) {
						languageJson = [];
						var jsonData = Json.parse(File.getContent(dir));
						var datas:Array<{
							zh:String
						}> = jsonData.data;
						for (item in datas) {
							languageJson[item.zh] = true;
						}
					} else {
						languageJson = [];
					}
				default:
					text += parserDir(dir);
			}
		}
		var path = Sys.programPath();
		path = Path.directory(path);
		var text_path = path + "/text.txt";
		File.saveContent(text_path, text);

		var csv = ["来自文件,文案"];
		for (value in list) {
			csv.push(value.by + "," + value.text);
		}
		File.saveContent("text.csv", csv.join("\n"));
	}

	public static function filterFunc(context:String):String {
		var req = ~/addProp\(.+\)/g;
		return context;
	}

	public static function parserDir(dir:String):String {
		var text = "";
		// 忽略编辑器目录代码
		if (dir.indexOf("game/display/editer") != -1) {
			return text;
		}
		if (dir.indexOf("GameSource/test") != -1) {
			return text;
		}
		if (FileSystem.exists(dir)) {
			var files = FileSystem.readDirectory(dir);
			for (file in files) {
				// 忽略翻译文件
				// if (file == "lang.json" || file == "events.json" || file == "worlddrop.json" || file == "buffs.json") {
				// continue;
				// }
				var path = dir + "/" + file;
				if (FileSystem.isDirectory(path)) {
					text += parserDir(path);
				} else {
					var ext = file.substr(file.lastIndexOf(".") + 1);
					switch (ext) {
						case "hx", "xml":
							// trace("处理：", path);
							var content = File.getContent(path);
							if (content.indexOf("@:ignoreLanguage") != -1)
								continue;
							// 排除ThinkData.+;
							var error = ~/ThinkData.+;/g;
							content = error.replace(content, "");
							// 排除SDKV4.reportCallStack
							var error = ~/SDKV4.reportCallStack\(.+\)/g;
							content = error.replace(content, "");
							// 排除V4Api.eventApi.reportError
							var error = ~/V4Api.eventApi.reportError\(.+\)/g;
							content = error.replace(content, "");
							// 排除throw
							var error = ~/throw.+;/g;
							content = error.replace(content, "");
							// 排除@:xxxx()格式
							var error = ~/@:[a-z]+\(.+\)/g;
							content = error.replace(content, "");
							// ZLog
							var error = ~/ZLog\..+\);/g;
							content = error.replace(content, "");
							// 排除errorMsg
							var error = ~/errorMsg:.+/g;
							content = error.replace(content, "");
							// 排除console.log
							var error = ~/console.log\(.+\)/g;
							content = error.replace(content, "");
							// 排除LogUtils.log
							var error = ~/LogUtils.log\(.+\)/g;
							content = error.replace(content, "");
							// 排除Console.error
							var error = ~/Console.error\(.+\)/g;
							content = error.replace(content, "");
							// 排除UserDataUtils.consumeDiamond(propcounts, false, null, true, "制作消耗");
							var consumeDiamond = ~/UserDataUtils.consumeDiamond\(.+\)/g;
							content = consumeDiamond.replace(content, "");
							// 排除UserDataUtils.addProp(taskData.materialid, Std.parseFloat(taskData.materialamount), "岛主任务");
							var addProp = ~/UserDataUtils.addProp\(.+\)/g;
							content = addProp.replace(content, "");
							// 排除GetPropsView.show\([^]+商店免费奖励[^]+\)
							var checkGetPropsViewShowApi = ~/GetPropsView.show\(.+\)/g;
							content = checkGetPropsViewShowApi.replace(content, "");
							// 排除trace
							var removeTrace = ~/trace\(.+\)/g;
							content = removeTrace.replace(content, "");
							var req = ~/"[^"]+"|'[^']+'|""|''/g;
							req.map(content, (s) -> {
								var t = s.matched(0);
								t = StringTools.replace(t, "'", "\"");
								// 检测里面必须要包含一个汉字
								var req2 = ~/[\u4E00-\u9FA5]/;
								if (req2.match(t)) {
									// 检查是否忽略
									// 检测是否已翻译，如果未翻译，则记录
									var key = t.substr(1);
									key = key.substr(0, key.length - 1);
									key = StringTools.replace(key, "\\n", "\n");
									if (igrone.indexOf(key) == -1) {
										if (!languageJson.exists(key.replace("\n", "\\n"))) {
											if (!keys.exists(t)) {
												list.push({
													text: t,
													by: file
												});
												keys.set(t, true);
											}
										}
									}
								}
								return t;
							});
							// text += File.getContent(path);
							text += "\n" + path + "\n";
							text += content;
					}
				}
			}
		} else
			throw dir + "路径不存在";
		return text;
	}

	/**
	 * 追加翻译文案
	 * @param char 
	 */
	public static function pushText(char:String):Void {}
}
